# -*- utf-8 -*-
# @Time: 2021/8/2 10:53
# @Author: CACode
from datetime import datetime

from rest_framework import serializers

from apps.baseData.models import (User, Province, City, District)


def range_name(count):
    if len(str(count)) <= 7:
        return '0'.join(['' for i in range(7 - count)]) + str(count + 1)
    return str(1000000 + count + 1)


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    name = serializers.CharField(allow_null=True, max_length=255, help_text="类型的名字")
    # password = serializers.CharField(max_length=32, help_text="密码,使用md5加密")
    phone = serializers.CharField(max_length=11, help_text="手机号")
    email = serializers.CharField(max_length=255, allow_null=True, help_text="邮箱")
    sex = serializers.BooleanField(default=False, help_text="0男1女")
    birthday = serializers.DateTimeField(allow_null=True, help_text="默认生日为2001-01-01")

    class Meta:
        fields = '__all__'
        model = User

    def create(self, validated_data):
        if not validated_data['name']:
            name = range_name(User.objects.count())
            validated_data['name'] = 'bang-' + name
        if not validated_data['birthday']:
            validated_data['birthday'] = datetime.strptime('2001-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
        return super(UserSerializer, self).create(validated_data)


class UserInvitationSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    name = serializers.CharField(allow_null=True, max_length=255, help_text="类型的名字")
    # password = serializers.CharField(max_length=32, help_text="密码,使用md5加密")
    phone = serializers.CharField(max_length=11, help_text="手机号")
    email = serializers.CharField(max_length=255, allow_null=True, help_text="邮箱")
    sex = serializers.BooleanField(default=False, help_text="0男1女")
    birthday = serializers.DateTimeField(allow_null=True, help_text="默认生日为2001-01-01")
    invitation = UserSerializer()

    class Meta:
        fields = '__all__'
        model = User


class DistrictSerializer(serializers.ModelSerializer):
    """区"""

    class Meta:
        model = District
        fields = '__all__'


class CityJoinSerializer(serializers.ModelSerializer):
    """市"""
    id = serializers.IntegerField(help_text='主键')
    name = serializers.CharField(max_length=255, help_text="市的名字")
    district = DistrictSerializer(many=True)

    class Meta:
        model = City
        fields = '__all__'


class CitySerializer(serializers.ModelSerializer):
    """市"""

    class Meta:
        model = City
        fields = '__all__'


class ProvinceJoinSerializer(serializers.ModelSerializer):
    """省"""
    city_set = CitySerializer(many=True)

    class Meta:
        model = Province
        fields = '__all__'


class ProvinceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Province
        fields = '__all__'
